from flaskapp.util.Sqlalchemy import db
from datetime import datetime

class User(db.Model):
    __tablename__ = 'user'

    user_id = db.Column(db.Integer, primary_key=True)
    account_name = db.Column(db.String(50), nullable=False, unique=True)
    username = db.Column(db.String(50), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False)
    is_admin = db.Column(db.Boolean, default=False, nullable=False)
    register_at = db.Column(db.DateTime, default=datetime.utcnow)
    phone = db.Column(db.String(20), nullable=True)
    life = db.Column(db.Integer, default=1, nullable=False)
    phone_verified = db.Column(db.Boolean, default=False, nullable=False)

    def __init__(self, account_name, username, password, is_admin=False, phone=None, life=1, phone_verified=False):
        self.account_name = account_name
        self.username = username
        self.password = password
        self.is_admin = is_admin
        self.register_at = datetime.utcnow()
        self.phone = phone
        self.life = life
        self.phone_verified = phone_verified

    def to_dict(self):
        return {
            'user_id': self.user_id,
            'account_name': self.account_name,
            'username': self.username,
            'is_admin': self.is_admin,
            'register_at': self.register_at.isoformat() if self.register_at else None,
            'phone': self.phone,
            'life': self.life,
            'phone_verified': self.phone_verified
        }

    def addUser(self):
        db.session.add(self)
        db.session.commit()

    def update_username(user_id, new_username):
        user = User.query.get(user_id)
        if user:
            user.username = new_username
            db.session.commit()

    def update_account_name(user_id, new_accountname):
        user = User.query.get(user_id)
        if user:
            user.account_name = new_accountname
            db.session.commit()

    def update_password(user_id, new_password):
        user = User.query.get(user_id)
        if user:
            user.password = new_password
            db.session.commit()

    def update_phone(user_id, new_phone, verified=True):
        user = User.query.get(user_id)
        if user:
            user.phone = new_phone
            user.phone_verified = verified
            db.session.commit()
            return True
        return False